package com.tupi.project.ui.presenter;

import com.google.gson.Gson;
import com.tupi.project.base.RxPresenter;
import com.tupi.project.component.CommonSubscriber;
import com.tupi.project.component.PreferencesHelper;
import com.tupi.project.http.HttpHelper;
import com.tupi.project.bean.BaseBean;
import com.tupi.project.bean.UserInfoBean;
import com.tupi.project.ui.contract.HttpContract;
import com.tupi.project.util.MD5Util;
import com.tupi.project.util.RxUtil;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/2.
 */

public class HttpPresenter extends RxPresenter<HttpContract.View> implements HttpContract.Presenter
{
    private HttpHelper mHttpHelper;
    private PreferencesHelper mPreferencesHelper;
    
    @Inject
    public HttpPresenter(HttpHelper httpHelper, PreferencesHelper preferencesHelper)
    {
        super();
        mHttpHelper = httpHelper;
        mPreferencesHelper = preferencesHelper;
    }
    
    
    @Override
    public void reqLogin(String acc, String pwd)
    {
        addSubscribe(mHttpHelper.reqLogin(acc, pwd)
                .compose(RxUtil.<BaseBean<String, UserInfoBean>>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<BaseBean<String, UserInfoBean>>(mView)
                {
                    @Override
                    public void onNext(BaseBean<String, UserInfoBean> stringUserInfoBeanBaseBean)
                    {
                        mView.showUserInfo(new Gson().toJson(stringUserInfoBeanBaseBean));
                        mPreferencesHelper.setToken(stringUserInfoBeanBaseBean.getObj().getToken());
                    }
                }));
    }
    
    @Override
    public boolean check(String acc, String pwd)
    {
        if (acc.length() == 0)
        {
            mView.showErrorMsg("账号不能为空");
            return false;
        }
        if (pwd.length() == 0)
        {
            mView.showErrorMsg("密码不能为空");
            return false;
        }
        return true;
    }
    
    @Override
    public void onClickLogin(String acc, String pwd)
    {
        if (check(acc, pwd))
        {
            reqLogin(acc, MD5Util.encryption(pwd));
        }
    }
    
    @Override
    public void onClickShowToken()
    {
        mView.showToken(mPreferencesHelper.getToken());
    }
    
    
    @Override
    public void addEvent()
    {
        
    }
}
